<template>
  <div>
    <el-upload
      v-if="isUpload"
      ref="elUpload"
      class="upload-demo"
      action="http://up-z1.qiniup.com"
      :data="qnFileData"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      :limit="maxFileLength"
      :on-exceed="handleExceed"
      :before-upload="beforeAvatarUpload"
      :on-success="handleAvatarSuccess"
      :file-list="fileList"
    >
      <el-button
        v-if="isUpload"
        size="small"
        type="primary"
      >点击上传</el-button></el-upload>
    <span v-else class="file-list">
      <div v-for="item of fileList" :key="item.Key" class="file-item">
        <a :href="item.value" target="_blank">{{ item.name }}</a>
      </div>
    </span>
  </div>
</template>
<script>
import { QNTokenRequest } from '@/api/index'
import { downloadFile } from '@/utils/downloadFile'
export default {
  name: 'Uploadele',
  props: {
    maxFileLength: { type: Number, default: 3 }, // 最大上传文件数量
    fileArr: { type: Array, default: () => [] },
    isUpload: { type: Boolean, default: true }, // 是否上传模式
    clsListBoolean: { type: Boolean } // 是否清空
  },
  data() {
    return {
      QNSrcHeader: 'http://qiniu.wqjsq.cn/',
      qnFileData: {
        token: ''
      },
      fileList: [],
      fileListSubmit: [], // 提交的数据
      FileType: '' // 文件类型
    }
  },
  watch: {
    clsListBoolean(newVal) {
      if (newVal) {
        this.fileList = []
        this.fileListSubmit = []
        this.$refs['elUpload'].clearFiles()
        this.$emit('clsRefresh', false)
      }
    },
    fileArr(newVal) {
      if (this.fileArr.length) {
        const fileList = []; const fileSubmitList = []
        const fileListData = this.fileArr
        fileListData.forEach((item) => {
          const itemData = {
            name: item.Key,
            value: item.Value + '?attname=' + item.Key
          }
          const submitData = {
            Key: item.Key,
            Value: item.Value
          }
          fileList.push(itemData)
          fileSubmitList.push(submitData)
        })
        this.fileList.splice(0, this.fileList.length, ...fileList)
        this.fileListSubmit = fileSubmitList
      } else {
        this.fileList.splice(0, this.fileList.length)
        this.fileListSubmit.splice(0, this.fileListSubmit.length)
        this.$refs['elUpload'].clearFiles()
      }
    }
  },
  created() {
    console.log(this.fileArr)
    if (!this.fileArr) {
      this.fileArr = []
    }
    if (this.fileArr.length) {
      const fileList = []; const fileSubmitList = []
      const fileListData = this.fileArr
      fileListData.forEach((item) => {
        const itemData = {
          name: item.Key,
          value: item.Value + '?attname=' + item.Key
        }
        const submitData = {
          Key: item.Key,
          Value: item.Value
        }
        fileList.push(itemData)
        fileSubmitList.push(submitData)
      })
      this.fileList.splice(0, this.fileList.length, ...fileList)
      this.fileListSubmit = fileSubmitList
    }
  },
  methods: {
    handlePreview(file) {
      // 下载
      console.log(file)
      downloadFile(file.value)
    },
    handleRemove(file, fileList) {
      // 附件删除
      const fileListSubmit = this.fileListSubmit
      const fileNameList = fileListSubmit.map((item) => item.Value)
      const spliceIndex = fileNameList.indexOf(file.name)
      fileListSubmit.splice(spliceIndex, 1)
      this.fileListSubmit = fileListSubmit
      this.fileList = fileList
      this.backDataMehods()
    },
    beforeRemove(file, fileList) {
      // 文件删除前确认
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.maxFileLength} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    handleAvatarSuccess(res, file) {
      this.fileList.push({
        name: this.FileType,
        value: this.QNSrcHeader + res.hash + '?attname=' + this.FileType
      })
      this.fileListSubmit.push({
        Value: this.QNSrcHeader + res.hash,
        Key: this.FileType
      })
      this.fileArr.splice(0, this.fileArr.length)
      for (var item of this.fileList) {
        this.fileArr.push({
          Key: item.name,
          Value: item.value.split('?')[0]
        })
      }
      this.backDataMehods()
    },
    QNTokenRequestFun() {
      return QNTokenRequest().then((res) => {
        if (res.state) this.qnFileData.token = res.data
      })
    },
    async beforeAvatarUpload(file) {
      // 文件上传前
      // this.qnFileData.key = file.name;
      var FileExt = file.name.replace(/.+\./, '')
      this.FileType = file.name
      await this.QNTokenRequestFun()
    },
    backDataMehods() {
      this.$emit('update:toFarUpload', this.fileListSubmit)
    }
  }
}
</script>
<style lang="less" scoped>
.file-list{
  .file-item{
    color:@color-main;
    padding-bottom: @block-space-y;
    a{
      color:@color-main;
    }
  }
  .file-item:last-child{
    padding-bottom: 0;
  }
}
</style>
